<template>
  <div>
    <h3>课程列表</h3>
    <div class="btn_new_wrapper">
      <el-button
        @click="$router.push(`/courses/create`)"
        size="medium"
        type="success"
      >
        新建
      </el-button>
    </div>
    <el-table
      :border="true"
      :data="data.data"
    >
      <el-table-column
        :key="name"
        :label="field.label"
        :prop="name"
        v-for="(field, name) in fields"
      ></el-table-column>

      <el-table-column
        label="操作"
      >
        <template slot-scope="{row}">
          <el-button
            @click="$router.push(`/courses/edit/${row._id}`)"
            size="small"
            type="success"
          >
            编辑
          </el-button>
          <el-button
            @click="remove(row)"
            size="small"
            type="danger"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
  import {Component, Vue} from 'vue-property-decorator'

  @Component({})
  export default class CoursesList extends Vue {
    data = {}

    fields = {
      _id: {
        label: 'ID'
      },
      name: {
        label: '课程名称'
      },
      cover: {
        label: '课程封面图'
      }
    }

    async fetch() {
      const res = await this.$http.get('courses')
      this.data = res.data
    }

    created() {
      this.fetch()
    }

    async remove(rowData) {
      try {
        await this.$confirm(`是否确认删除？`)
      } catch (e) {
        return
      }
      await this.$http.delete(`courses/${rowData._id}`)
      this.$message.success(`删除成功`)
      await this.fetch()
    }
  }
</script>

<style scoped>
  .btn_new_wrapper {
    margin-bottom: 10px;
  }
</style>
